package com.ktjy.controller;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.dto.ActivityDTO;
import com.ktjy.pojo.SysUser;
import com.ktjy.pojo.TbActivity;
import com.ktjy.service.ITbActivityService;
import com.ktjy.utils.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * <p>
 * 活动管理 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-08-02
 */
@RestController
@RequestMapping("/api/tb/activity")
public class TbActivityController {
    Logger log = LoggerFactory.getLogger(TbActivityController.class);

    @Autowired
    ITbActivityService activityService;

    @GetMapping("/list")
    public AjaxResult list(ActivityDTO activityDTO,
                           @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        IPage<TbActivity> page = activityService.findPage(activityDTO, pageNo, pageSize);
        return AjaxResult.success(page);
    }

    @PostMapping("/save")
    public AjaxResult saveOrUpdate(@RequestBody TbActivity tbActivity) {
        try {

            //自动生成活动编号
            if (tbActivity.getId() == null && tbActivity.getCode() == null) {
                // 生成8位随机字符串（包含大小写字母和数字）
                tbActivity.setCode(generateRandomCode(8));
            }
            boolean ok = activityService.saveOrUpdate(tbActivity);
            if (ok) {
                return AjaxResult.success("保存成功");
            }
        } catch (Exception e) {
            log.error("TbActivityController中saveOrUpdate方法执行报错的。", e);
        }
        return AjaxResult.error("保存失败");
    }
    /**
     * 生成指定长度的随机字符串（包含大小写字母和数字）
     */
    private String generateRandomCode(int length) {
        // 字符源：包含大小写字母和数字
        String charSource = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder codeBuilder = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            // 随机从字符源中获取一个字符
            int index = random.nextInt(charSource.length());
            codeBuilder.append(charSource.charAt(index));
        }

        return codeBuilder.toString();
    }
    @GetMapping("/view/{id}")
    public AjaxResult view(@PathVariable("id") Long id) {
        //查询详情
        try {
            TbActivity tbActivity = activityService.getById(id);
            if (tbActivity != null) {
                return AjaxResult.success(tbActivity);
            }
        } catch (Exception e) {
            log.error("TbActivityController中view方法执行报错的。", e);
        }
        return AjaxResult.error();
    }

    @DeleteMapping("/del/{id}")
    public AjaxResult del(@PathVariable("id") Long id) {
        try {
            boolean ok = activityService.removeById(id);
            if (ok) {//删除成功
                return AjaxResult.success("删除成功");
            }
        } catch (Exception e) {
            log.error("TbActivityController中del方法执行报错的。", e);
        }
        return AjaxResult.error("删除失败");
    }

    @PutMapping("/pass")
    public AjaxResult pass(@RequestBody TbActivity tbActivity) {
        try {
            boolean ok = activityService.updateById(tbActivity);
            if (ok) {
                return AjaxResult.success();
            }
        } catch (Exception e) {
            log.error("TbActivityController中pass方法执行报错的。", e);
        }
        return AjaxResult.error();
    }

    @PutMapping("/reject")
    public AjaxResult reject(@RequestBody TbActivity tbActivity) {
        try {
            boolean ok = activityService.updateById(tbActivity);
            if (ok) {
                return AjaxResult.success();
            }
        } catch (Exception e) {
            log.error("TbActivityController中reject方法执行报错的。", e);
        }
        return AjaxResult.error();
    }
}
